<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <style>
    body {
      height: 200vh;
    }
  </style>
  <body>
    <h1>测试防抖请在此输入，并观察控制台</h1>
    <input type="text" />
    <h1>测试节流请滚动网页，并观察控制台</h1>
  </body>

  <script>
    const input = document.querySelector("input")

    function onInput(event) {
      console.log(event)
    }

    function debounce(func, delay) {
      let timer

      return function (event) {
        timer && clearTimeout(timer)

        timer = setTimeout(() => {
          func(event)
        }, delay)
      }
    }

    input.addEventListener("input", debounce(onInput, 1000))

    console.dir(debounce)
  </script>

  <script>
    function throttle(func, delay) {
      let timer

      return function () {
        if (timer) return

        timer = setTimeout(() => {
          func.apply(this, arguments)

          timer = null
        }, delay)
      }
    }

    function onScroll() {
      console.log("滚动了")
    }

    document.addEventListener("scroll", throttle(onScroll, 1000))
  </script>
</html>
